/**
 * Copyright 2014 opencxa.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.cxa.rpc.messages;

import java.util.Map;

import org.cxa.misc.NumberUtils;


/**
 * @author Christopher Armenio
 *
 */
public class RequestRpcMessage extends RpcMessage
{
	public RequestRpcMessage(RpcMessage msgIn)
	{
		super(msgIn);
	}
	
	
	public RequestRpcMessage(String destPathIn, String cmdIn, Map<String, Object> paramsIn)
	{
		super(destPathIn, cmdIn, paramsIn);
	}
	
	
	public Integer getId()
	{
		return this.id;
	}
	
	
	public void setId(Integer idIn)
	{
		this.id = idIn;
	}
		
	
	public String getDestination()
	{
		return this.dest;
	}
	
	
	public void setDestination(String destIn)
	{
		this.dest = destIn;
	}
	
	
	public String getCommand()
	{
		return this.cmd;
	}
	
	
	public Map<String, Object> getParameters()
	{
		return this.params;
	}
	
	
	public Object getParameter_byName(String nameIn)
	{
		return this.params.get(nameIn);
	}
	
	
	@SuppressWarnings("unchecked")
	public Object getParameter_byNameAndExpectedType(String nameIn, Class<?> expectedTypeIn)
	{
		Object retVal = (this.params != null) ? this.params.get(nameIn) : null;
		if( retVal == null ) return null;
		else if( expectedTypeIn.isInstance(retVal) ) return retVal;
		
		// if we made it here, we have a little more work to do before we can return our value
		if( retVal instanceof Number )
		{
			if( Number.class.isAssignableFrom(expectedTypeIn) ) retVal = NumberUtils.castToClass_strict((Number)retVal, (Class<Number>)expectedTypeIn);
			else if( expectedTypeIn == String.class ) retVal = ((Number)retVal).toString();
		}
		
		return retVal;
	}
	
	
	public void addParameter(String parameterNameIn, Object parameterIn)
	{
		if( (parameterNameIn == null) || (parameterNameIn.isEmpty()) ) throw new IllegalArgumentException("paramterName must be a non-null, non-empty String");
		this.params.put(parameterNameIn, parameterIn);
	}
}
